/**
 * 
 */
package com.ch03.UserBuy;
import java.util.*;
import com.ch03.UserTxn.*;
import com.ch03.Exception.*;
import com.ch03.TransactionTypeEnum.*;

/**
 * @author Swetha
 *
 */
public class UserBuy {
	
	private double initialBalance;
	private ArrayList<UserTransaction> transactions;
	private double shortAmount;
	
    public UserBuy()
    {
    	initialBalance = 0.0;
    	transactions = new ArrayList<UserTransaction>();
    }
    
    public UserBuy(double bal, ArrayList<UserTransaction> tran)
    {
    	initialBalance = bal;
    	transactions = tran;
    }

	public double getInitialBalance() {
		return initialBalance;
	}

	public void setInitialBalance(double initialBalance) {
		this.initialBalance = initialBalance;
	}

	public ArrayList<UserTransaction> getTransactions() {
		return transactions;
	}

	public void setTransactions(ArrayList<UserTransaction> transactions) {
		this.transactions = transactions;
	}
    
	public boolean canBuy(UserTransaction uTran) throws UserByException
	{
		double balance = 0.0;
		ArrayList<UserTransaction> userTran = new ArrayList<UserTransaction>();
				
		balance = getInitialBalance();
		userTran = getTransactions();
		
		// sum up all transactions in ArrayList
		for (UserTransaction i : userTran)
		{
	        if (i.getTransactionType() == TransactionType.BUY)
			{
				balance -= i.getTransactionAmt();
			}
			else if (i.getTransactionType() == TransactionType.SELL)
			{
				 balance += i.getTransactionAmt();
			}
		}
		
		if (uTran.getTransactionType() == TransactionType.BUY) {
			balance -= uTran.getTransactionAmt();
		} else {
			balance += uTran.getTransactionAmt();
		}
		
		System.out.println("Checking for available amount.....");
		// check for available balance amount
		if (balance >= 0)
		{
			System.out.println("Enough money available. Proceeding with the transaction...");
			return true;
		}
		else
		{
			shortAmount = -1 * balance;
			throw new UserByException("You are short by this amount", this);
		}
	}

	public double getShortAmount() {
		return shortAmount;
	}

	public void setShortAmount(double shortAmount) {
		this.shortAmount = shortAmount;
	}
}
